
import java.net.*;
import java.io.*;

public class TcpServer {

	private TheaterDatabase theaterDatabase;

	public static void main(String[] args) {

		try {
			int id = Integer.valueOf(args[0]);
			if (id < 0 || id >= Constants.NUM_SERVERS) {
				throw new Exception();
			}
			new TcpServer(id);
		} catch (Exception e) {
			System.out.println("\nInvalid argumnets!");
			System.out.println("Usage:");
			System.out.println("\tjava TcpServer <server id>");
			System.out.println("server ids = {0 ... " + (Constants.NUM_SERVERS - 0) + "}");
		}

	}

	public TcpServer(int id) {
		int port = Constants.getPort(id);
		System.out.println("Starting TCP Server port: " + port);
		try {
			ServerSocket serverSocket = new ServerSocket(port);
			theaterDatabase = new TheaterDatabase(id);
			while (true) {
				Socket socket = serverSocket.accept();
				if (socket != null) {
					TcpThread thread = new TcpThread(socket, theaterDatabase);
					thread.start();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class TcpThread extends Thread {

		Socket socket = null;
		TheaterDatabase theaterDatabase = null;
		BufferedReader bufferedReader;
		PrintWriter printWriter;

		public TcpThread(Socket socket, TheaterDatabase theaterDatabase) {
			this.socket = socket;
			this.theaterDatabase = theaterDatabase;
		}

		public void run() {
			try {
				// handle all incoming communication to this server
				// some are from the client and some are from other servers

				bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				printWriter = new PrintWriter(socket.getOutputStream(), true);
				String requestString = bufferedReader.readLine();
				String responseString = theaterDatabase.process(requestString);
				responseString = responseString.replace("\n", Constants.CARRIAGE_RETURN);
				printWriter.println(responseString + "\n");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
